//
//  JQFYSettingUserInfoViewController.m
//  JQFY
//
//  Created by 代辉 on 2017/10/2.
//  Copyright © 2017年 yannis. All rights reserved.
//

#import "JQFYSettingUserInfoViewController.h"
#import "JQFYTabbarController.h"
#import <TZImagePickerController.h>

@interface JQFYSettingUserInfoViewController () <UITextFieldDelegate,TZImagePickerControllerDelegate>

@property (nonatomic,weak) UIButton *selectedBtn;
@property (nonatomic,weak) UITextField *nameField;
@property (nonatomic,weak) UIButton *iconBtn;
@property (nonatomic,weak) UIImageView *welcome;
@property (nonatomic,assign) BOOL setIcon;
@property (nonatomic,weak) UIImage *iconImage;

@end

@implementation JQFYSettingUserInfoViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.view.layer.contents = (id)[UIImage imageNamed:@"enter_bg"].CGImage;
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillShow)
                                                 name:UIKeyboardWillShowNotification
                                               object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(keyboardWillHide)
                                                 name:UIKeyboardWillHideNotification
                                               object:nil];
    [self setupUI];
}

- (void)setupUI
{
    UIImageView *welcome = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"Welcome"]];
    [self.view addSubview:welcome];
    [welcome mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.top.equalTo(self.view).offset(62 *SCAL);
    }];
    self.welcome = welcome;
    
    UIImageView *unLogo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"unlogo_u"]];
    [self.view addSubview:unLogo];
    [unLogo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(welcome.mas_bottom).offset(11 *SCAL);
        make.centerX.equalTo(self.view);
    }];
    
    UIButton *iconBtn = [UIButton new];
    iconBtn.adjustsImageWhenHighlighted = NO;
    UIImage *bgImage = [UIImage imageNamed:@"组5（合并）"];
    [iconBtn setBackgroundImage:bgImage forState:UIControlStateNormal];
    [iconBtn addTarget:self action:@selector(settingIcon) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:iconBtn];
    [iconBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(unLogo.mas_bottom).offset(21 *SCAL);
        make.centerX.equalTo(self.view);
        make.size.mas_equalTo(CGSizeMake(160 *SCAL, 160 *SCAL));
    }];
    iconBtn.layer.cornerRadius = 80 *SCAL;
    iconBtn.layer.masksToBounds = YES;
    self.iconBtn = iconBtn;
    
    UITextField *nameField = [UITextField new];
    nameField.textAlignment = NSTextAlignmentCenter;
    nameField.placeholder = @"请输入您的昵称";
    nameField.font = [UIFont systemFontOfSize:13];
    nameField.textColor = [UIColor whiteColor];
    [nameField setValue:[UIColor whiteColor] forKeyPath:@"_placeholderLabel.textColor"];
    nameField.background = [UIImage imageNamed:@"text_bg"];
    [self.view addSubview:nameField];
    [nameField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(iconBtn.mas_bottom).offset(52 *SCAL);
        make.centerX.equalTo(self.view);
        make.width.mas_equalTo(256 *SCAL);
        make.height.mas_equalTo(37 *SCAL);
    }];
    nameField.delegate = self;
    self.nameField = nameField;
    
    UIButton *boy = [UIButton new];
    [boy setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
    [boy setTitle:@"BOY" forState:UIControlStateNormal];
    [boy setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [boy setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [boy setBackgroundImage:[UIImage imageNamed:@"gender_bg"] forState:UIControlStateSelected];
    [boy addTarget:self action:@selector(boy:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:boy];
    [boy mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameField.mas_bottom).offset(22 *SCAL);
        make.left.equalTo(nameField);
    }];
    
    UIButton *girl = [UIButton new];
    [girl setBackgroundImage:[UIImage imageNamed:@"btn_bg"] forState:UIControlStateNormal];
    [girl setTitle:@"GIRL" forState:UIControlStateNormal];
    [girl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [girl setTitleColor:[UIColor blackColor] forState:UIControlStateSelected];
    [girl setBackgroundImage:[UIImage imageNamed:@"gender_bg"] forState:UIControlStateSelected];
    [girl addTarget:self action:@selector(girl:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:girl];
    [girl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(nameField.mas_bottom).offset(22 *SCAL);
        make.right.equalTo(nameField);
    }];
    self.selectedBtn.selected = NO;
    
    UIButton *enterButton = [UIButton new];
    [enterButton setBackgroundImage:[UIImage imageNamed:@"确认（合并）"] forState:UIControlStateNormal];
    [self.view addSubview:enterButton];
    [enterButton addTarget:self action:@selector(enter) forControlEvents:UIControlEventTouchUpInside];
    [enterButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(boy.mas_bottom).offset(30 *SCAL);
        make.centerX.equalTo(self.view);
    }];
    
    UIImageView *logo = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"logo（合并）"]];
    [self.view addSubview:logo];
    [logo mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self.view);
        make.bottom.equalTo(self.view).offset(-30 *SCAL);
    }];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if (self.nameField.editing) {
        [[NSUserDefaults standardUserDefaults] setObject:self.nameField.text forKey:@"nickName"];
        [self.nameField resignFirstResponder];
    }
    
}
#pragma mark - boy -
- (void)boy:(UIButton *)button
{
    if (self.selectedBtn == button) {
        return;
    }
    if (self.selectedBtn) {
        self.selectedBtn.selected = NO;
        [self.selectedBtn setTintColor:[UIColor whiteColor]];
    }
    button.selected = YES;
    [button setTintColor:[UIColor lightGrayColor]];
    self.selectedBtn = button;
    
}
#pragma mark - girl -
- (void)girl:(UIButton *)button
{
    if (self.selectedBtn == button) {
        return;
    }
    if (self.selectedBtn) {
        self.selectedBtn.selected = NO;
        [self.selectedBtn setTintColor:[UIColor whiteColor]];
    }
    button.selected = YES;
    [button setTintColor:[UIColor lightGrayColor]];
    self.selectedBtn = button;
}

#pragma mark - 点击确认进入 -
- (void)enter
{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.removeFromSuperViewOnHide = YES;
    hud.mode = MBProgressHUDModeCustomView;
    JQFYUserData *data = [JQFYUserData sharedData];
    data.isSetting = YES;
    [data saveUserInfo];
    if (!self.setIcon || !self.selectedBtn || self.nameField.text.length == 0) {
        hud.detailsLabelText = @"请补全个人信息";
        [hud hide:YES afterDelay:1];
        return;
    }
    NSData *iconData = UIImageJPEGRepresentation(self.iconImage, 0.01);
    NSString *sex;
    if ([self.selectedBtn.titleLabel.text isEqualToString:@"BOY"]) {
        sex = @"男";
    } else {
        sex = @"女";
    }
    NSDictionary *dict = @{
                           @"token":[JQFYUserData userDataInSandbox].token,
//                           @"head":iconData,
                           @"sex":sex,
                           @"nickname":self.nameField.text
                           };
    
    [[AFHTTPSessionManager manager] POST:@"http://app.uninhibited.cn/api/user/adduser"
                              parameters:dict constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
                                  NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
                                  formatter.dateFormat = @"yyyyMMddHHmmss";
                                  NSString *str = [formatter stringFromDate:[NSDate date]];
                                  NSString *fileName = [NSString stringWithFormat:@"%@.png", str];
                                  [formData appendPartWithFileData:iconData name:@"head" fileName:fileName mimeType:@"image/png"];
                              }
                                progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                                    if ([responseObject[@"status"] isEqualToString:@"error"]) {
                                        hud.detailsLabelText = @"上传失败";
                                    } else {
                                        
                                        hud.detailsLabelText = @"上传成功";
                                         [UIApplication sharedApplication].keyWindow.rootViewController = [[JQFYTabbarController alloc]init];
                                    }
                                    
                                    [hud hide:YES afterDelay:1];
                                    
                                } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                                    if (error) {
                                        hud.detailsLabelText = @"上传失败";
                                        [hud hide:YES afterDelay:1];
                                    }
                                }];
}

#pragma mark - UITextFieldDelegate -
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    [[NSUserDefaults standardUserDefaults] setObject:textField.text forKey:@"nickName"];
    return YES;
}

- (void)settingIcon
{
    TZImagePickerController *imagePickerVc = [[TZImagePickerController alloc] initWithMaxImagesCount:9 delegate:self];
    imagePickerVc.maxImagesCount = 1;
    imagePickerVc.naviBgColor = [UIColor colorWithHex:0x694CE6];
    imagePickerVc.showSelectBtn = NO;
    imagePickerVc.isSelectOriginalPhoto = NO;
    imagePickerVc.allowTakePicture = NO;
    imagePickerVc.allowPickingVideo = NO;
    imagePickerVc.allowCrop = YES;
    imagePickerVc.cropRect = CGRectMake(0, (DH_Screen_Height - DH_Screen_Width) / 2, DH_Screen_Width, DH_Screen_Width);
    [imagePickerVc setDidFinishPickingPhotosHandle:^(NSArray<UIImage *> *photos, NSArray *assets, BOOL isSelectOriginalPhoto) {
        self.setIcon = YES;
        [self.iconBtn setBackgroundImage:photos[0] forState:UIControlStateNormal];
        self.iconImage = photos[0];
    }];
    [self presentViewController:imagePickerVc animated:YES completion:nil];
}
#pragma mark - 监听键盘弹出 -
- (void)keyboardWillShow
{
    [self.welcome mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(42 *SCAL);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

#pragma mark - 监听键盘将要消失 -
- (void)keyboardWillHide
{
    [self.welcome mas_updateConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view).offset(62 *SCAL);
    }];
    [UIView animateWithDuration:0.25 animations:^{
        [self.view layoutIfNeeded];
    }];
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}
@end
